/**
 * IPFilter.java<br>
 *
 *
 * @version 下午11:03:48
 */
package com.iwechat.adapter.mina.filter;

import java.net.InetSocketAddress;
import java.net.SocketAddress;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.mina.core.filterchain.IoFilterAdapter;
import org.apache.mina.core.session.IoSession;
import org.springframework.beans.factory.annotation.Autowired;

import com.iwechat.emuns.ConstEmus;
import com.iwechat.service.ClientFactory;

/**
 * IP白名单过滤器
 *
 *
 */
public class IPFilter extends IoFilterAdapter {
    private static final Logger logger = LogManager.getLogger();
    @Autowired
    ClientFactory               cfactory;

    /*
     * (non-Javadoc)
     *
     * @see org.apache.mina.core.filterchain.IoFilterAdapter#sessionCreated(org.apache.mina.core.filterchain.IoFilter.NextFilter,
     * org.apache.mina.core.session.IoSession)
     */
    @Override
    public void sessionCreated(NextFilter nextFilter, IoSession session) throws Exception {
        SocketAddress addr = session.getRemoteAddress();
        String clientIp = ((InetSocketAddress) addr).getAddress().getHostAddress();
        if (cfactory.checkIP(clientIp)) {
            session.setAttribute(ConstEmus.clientIp.value(), clientIp);
            super.sessionCreated(nextFilter, session);
        } else {
            logger.error("sessionId[" + session.getId() + "] IP地址[" + clientIp + "]不在系统白名单中,请确认.");
            session.closeNow();
        }
    }

}
